package com.chookss.home.logContacts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.LogManagerEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

public class LogManagersActivity extends BaseAct {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvTitleInit)
    TextView tvTitleInit;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.common_right_iv)
    ImageView common_right_iv;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.tvEmpty)
    TextView tvEmpty;
    private LogGroupsAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<LogManagerEntity> list = new ArrayList<>();
    private int type = 0;//默认0是编辑 1是选择分组
    private int reportType = 0;  // 0 日报 1 周报 2 月报 3 日志
    private String typeName = "";//选择分类的名称
    private int indexChoice = -1;//选择分类的下标
    private String teamCode = "";//修改分组之前选中的
    private String employeecode = "";//登录人的code  判断是否是自己管理的分组

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_log_managers);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 0);
        reportType = getIntent().getIntExtra("reportType", 0);
        typeName = getIntent().getStringExtra("typeName");
        teamCode = getIntent().getStringExtra("teamCode");
        employeecode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        if (type == 0) {
            common_title_txt.setText("管理分组");
            common_right_iv_ll.setVisibility(View.VISIBLE);
            common_right_iv.setBackgroundResource(R.drawable.icon_add_46);
        } else {
            if (type == 1) {
                common_title_txt.setText(typeName);
            }
            tvTitleInit.setVisibility(View.VISIBLE);
            common_right_txt.setVisibility(View.VISIBLE);
            common_right_txt.setText("确定");
            common_right_txt.setTextColor(getResources().getColor(R.color.main_color));
            tvEmpty.setText("暂无" + typeName + "分组");
            tvTitleInit.setText("请选择将" + typeName + "发布的分组，无选择时，将默认按组织机构可见。");
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new LogGroupsAdapter(R.layout.item_log_group, this, list);
        recyclerView.setAdapter(adapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<LogManagerEntity>>>() {
        }.getType(), null, Urls.selectReportTeamList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<LogManagerEntity>>() {
            @Override
            public void onSuccess(List<LogManagerEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (common_right_txt == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (type == 0) {
                        //正常情况 显示自己是管理员的分组
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getOwerEmployeeCode().equals(employeecode)) {
                                list.add(data.get(i));
                            }
                        }
                        if (list.size() == 0) {
                            smrRf.setVisibility(View.GONE);
                            llNone.setVisibility(View.VISIBLE);
                        } else {
                            adapter.notifyDataSetChanged();
                            smrRf.setVisibility(View.VISIBLE);
                            llNone.setVisibility(View.GONE);
                        }
                    } else {
                        //展示  与发布内容相对应的分组
                        for (int i = 0; i < data.size(); i++) {
                            if (reportType == Utils.changeNumber(data.get(i).getReportType())) {
                                list.add(data.get(i));
                                if (teamCode.equals(data.get(i).getTeamCode())) {
                                    indexChoice = list.size() - 1;
                                }
                            }
                        }
                        if (list.size() == 0) {
                            smrRf.setVisibility(View.GONE);
                            llNone.setVisibility(View.VISIBLE);
                            common_right_txt.setVisibility(View.GONE);
                        } else {
                            adapter.notifyDataSetChanged();
                            smrRf.setVisibility(View.VISIBLE);
                            llNone.setVisibility(View.GONE);
                        }
                    }


                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        common_right_txt.setVisibility(View.GONE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    class LogGroupsAdapter extends BaseQuickAdapter<LogManagerEntity, BaseViewHolderEx> {
        private Context context;

        public LogGroupsAdapter(int layoutResId, Context context, @Nullable List<LogManagerEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, LogManagerEntity item) {
            RelativeLayout rl = helper.getView(R.id.rl);
            ImageView ivChoice = helper.getView(R.id.ivChoice);
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvInit = helper.getView(R.id.tvInit);
            tvTitle.setText(item.getTeamName());
            if ("0".equals(item.getReportType())) {
                tvType.setText("日报");
            } else if ("1".equals(item.getReportType())) {
                tvType.setText("周报");
            } else if ("2".equals(item.getReportType())) {
                tvType.setText("月报");
            } else if ("3".equals(item.getReportType())) {
                tvType.setText("日志");
            } else {
                tvType.setText("分组");
            }
            if (type == 1) {
                rl.setVisibility(View.VISIBLE);
                if (indexChoice == helper.getItemPosition()) {
                    ivChoice.setBackgroundResource(R.drawable.icon_fx_select);
                } else {
                    ivChoice.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                }
            } else {
                rl.setVisibility(View.GONE);
            }

            rl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (indexChoice == helper.getItemPosition()) {
                        indexChoice = -1;
                    } else {
                        indexChoice = helper.getItemPosition();
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            tvInit.setText("成员共" + item.getEmpNum() + "人");
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(LogManagersActivity.this, LogManagerEditActivity.class);
                    intent.putExtra("id", item.getId());
                    if (type == 1) {
                        intent.putExtra("type", 2);
                    }
                    startActivity(intent);
                }
            });

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshLogMangerFragment".equals(msg)) {
                //刷新最近列表
                isEnd = false;
                currentPage = 1;
                getData();
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt, R.id.common_right_iv_ll})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                intent = new Intent();
                if (indexChoice < 0) {
                    intent.putExtra("teamName", "");
                    intent.putExtra("teamCode", "");
                } else {
                    intent.putExtra("teamName", list.get(indexChoice).getTeamName());
                    intent.putExtra("teamCode", list.get(indexChoice).getTeamCode());
                }
                setResult(1000, intent);
                finish();
                break;
            case R.id.common_right_iv_ll:
                intent = new Intent(this, LogManagerEditActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("name", "新建分组" + (list.size() + 1));
                startActivity(intent);
                break;
        }
    }
}
